import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_syt/datas/image_response.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/image_picker_helper.dart';
import 'package:provider/provider.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/widgets/common_dialog.dart';
import 'package:flutter_syt/domain/widgets/custom_dialog.dart';
import 'package:flutter_syt/domain/widgets/list_item.dart';
import 'package:flutter_syt/domain/widgets/sex_select.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '../../global_easy_loading.dart';

@RoutePage(name: "editUserInfoPage")
class EditUserInfoPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _EditUserInfoPageState();
  }
}

class _EditUserInfoPageState extends State<EditUserInfoPage> {
  int selectedSex = 1;

  String selectedBirthday = '1990-01-01';

  onSexChange(int sex) {
    selectedSex = sex;
  }

  onBirthdayChange(DateTime dateTime) {
    selectedBirthday = DateUtil.formatDate(dateTime, format: 'yyyy-MM-dd');
  }

  _pickImage() async {
    int index = await DialogHelper.showBottom(context);
    if (index == null || index == 2) {
      return;
    }
    await Future.delayed(Duration(milliseconds: 500)); // Add this line
    final pickedFile =
        await ImageHelper.pickSingleImage(context, source: index);
    if (pickedFile != null) {
      try {
        File imageFile = await ImageHelper.cropImage(context, pickedFile.path);
        _uploadImage(imageFile.path);
      } catch (e) {
        customShowToast(S().img_pro_failed);
      }
    }
  }

  _uploadImage(String filePath) async {
    ImageResponse img = await API.shared.common.uploadImage(filePath);
    await API.shared.user.updateUserInfo('avatar', img.url);
    customShowSuccess(S.of(context).avatar_upload_success_toast);
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<UserInfo>(builder: (ctx, user, child) {
      return _build(ctx, user);
    });
  }

  Widget _build(BuildContext context, UserInfo me) {
    List<ListItemEntity> listData = [
      ListItemEntity(
        S.of(context).profile_photo,
        null,
        '',
        () {
          _pickImage();
        },
        customRight: Container(
          child: CircleAvatar(
            backgroundImage: NetworkImage(
              me.avatar,
            ),
          ),
        ),
      ),
      ListItemEntity(
        S.of(context).username,
        null,
        S.of(context).user_nickname,
        () => {
          // RouteManager.push(
          //   context,
          //   RoutMapping.editUserNickNamePage(),
          // ),
        },
        isShowRightIcon: false,
      ),
      ListItemEntity(
        S.of(context).gender,
        null,
        me.sex == 1
            ? S.of(context).male
            : me.sex == 2
                ? S.of(context).female
                : S.of(context).gender_unknow,
        () => {
          showCommonDialog(
            context,
            DialogEntity(
              S.of(context).set_gender,
              Container(
                padding: EdgeInsets.symmetric(horizontal: 10),
                child: Column(
                  children: [
                    Text(
                      S.of(context).Gender_Set,
                      style: FontStyles.headerTextStyle_14.copyWith(
                        color: ThemeColor.colorBlack40,
                      ),
                    ),
                    SexSelect(onSexChange, me.sex),
                  ],
                ),
              ),
              () {
                Navigator.of(context).pop();
              },
              () async {
                await API.shared.user.updateUserInfo(
                  'sex',
                  selectedSex,
                );
                Navigator.of(context).pop();
              },
              cancelText: S.of(context).cancel,
              okText: S.of(context).confirm,
              contentPadding: EdgeInsets.only(bottom: 0),
            ),
          )
        },
      ),
      ListItemEntity(
        S.of(context).birthday,
        null,
        me.birthday,
        () => {
          showCommonDialog(
            context,
            DialogEntity(
              S.of(context).birthday_Set,
              Container(
                height: 220,
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.date, //这里改模式
                  maximumDate: DateTime.now(),
                  initialDateTime: me.birthday != ''
                      ? DateUtil.getDateTime(me.birthday)
                      : DateTime(1990),
                  onDateTimeChanged: (dateTime) {
                    // print("${dateTime.year}-${dateTime.month}-${dateTime.day}");
                    onBirthdayChange(dateTime);
                  },
                ),
              ),
              () {
                Navigator.of(context).pop();
              },
              () async {
                await API.shared.user
                    .updateUserInfo('birthday', selectedBirthday);
                Navigator.of(context).pop();
                // print(selectedBirthday);
              },
              cancelText: S.of(context).cancel,
              okText: S.of(context).confirm,
              contentPadding: EdgeInsets.only(bottom: 0),
            ),
          )
        },
        isShowBorder: false,
      ),
    ];

    return Scaffold(
      appBar: AppBar(
        title: Text(
          S.of(context).edit_profile,
        ),
      ),
      body: Column(
        children: [
          Container(
            margin: EdgeInsets.all(10.0),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              color: ThemeColor.bkColorFFFFFF,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: listData
                  .map((e) => GestureDetector(
                        onTap: ClickUtils.debounce(() => e.onTap),
                        child: Container(
                          // color: Colors.blueGrey,
                          alignment: Alignment.center,
                          child: ListItem(e),
                        ),
                      ))
                  .toList(),
            ),
          ),
        ],
      ),
    );
  }
}
